<template>
  <div>
    <div class="content" v-if="!isDetail">
      <el-button
        v-if="userInfo._id"
        size="mini"
        type="danger"
        @click="doPublish"
        >我要发布</el-button
      >
      <el-dialog
        title="发布"
        :visible.sync="isVisible"
        width="50%"
        :before-close="handleClose"
      >
        <el-form
          :model="form"
          :rules="rules"
          ref="form"
          label-width="100px"
          class="demo-form"
        >
          <el-form-item label="名称" prop="squareName">
            <el-input v-model="form.squareName"></el-input>
          </el-form-item>
          <el-form-item label="内容" prop="squareContent">
            <el-input
              :autosize="{ minRows: 5, maxRows: 10 }"
              type="textarea"
              v-model="form.squareContent"
            ></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button size="mini" @click="isVisible = false">取 消</el-button>
          <el-button size="mini" type="primary" @click="commit"
            >发 布</el-button
          >
        </span>
      </el-dialog>
      <div
        class="each-square"
        @click="toDetail(item)"
        v-for="(item, index) in tableDataFilter"
        :key="index"
      >
        <div class="flex-center">
          <img :src="item.userData.avator" alt="" />
          <div class="header">
            <div>{{ item.userData.username }}</div>
            <div v-if="item.userData.companyName">
              {{ item.userData.companyName }}
            </div>
          </div>
        </div>
        <div class="squareName">{{ item.squareName }}</div>
        <div class="squareContent">{{ item.squareContent }}</div>

        <div class="detail">查看详情</div>
      </div>

      <div class="pagination" v-if="tableDataFilter.length">
        <el-pagination
          background
          layout="prev, pager, next"
          :current-page.sync="pageNum"
          @current-change="handleCurrentChange"
          :page-size="pageSize"
          :total="total"
        >
        </el-pagination>
      </div>
    </div>
    <div class="content" v-if="isDetail">
      <div class="back" @click="isDetail = false;">返回</div>
      <div class="squareName">{{ current.squareName }}</div>
      <div style="color: #333;margin-bottom: 10px;">发布人：{{ current.userData.username }}</div>
      <div class="sqd">{{ current.squareContent }}</div>
      <div class="comments">
        <div class="add" v-if="userInfo._id">
          <el-input
            type="textarea"
            placeholder="请输入评论"
            v-model="comment"
            :autosize="{ minRows: 3, maxRows: 4}"
            maxlength="200"
            show-word-limit
          >
          </el-input>
          <el-button type="primary" @click="addCom">添加</el-button>
        </div>
        <div v-for="item in commentList" class="each">
          <div class="flex-center">
            <img class="avator" :src="item.userInfo.avator" alt="">
            <div class="username">{{ item.userInfo.username }}</div>
          </div>
          <div style="color: #666;">
            {{ item.commentContent }}
          </div>
          <div @click="doDelete(item)" v-if="item.userInfo._id === userInfo._id" class="delete">删除</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getUserInfo, getSquare, addSquare, getComments, addComment, deleteComment } from "../service.js";
export default {
  name: "publish",
  beforeCreate() {},
  mounted() {
    if (localStorage.getItem("meiyaWebInfo")) {
      this.userInfo = JSON.parse(localStorage.getItem("meiyaWebInfo"));
      getUserInfo(this.userInfo._id).then((res) => {
        this.userInfo = res.data;
      });
    }
    this.refreshTable();
  },
  data() {
    return {
      comment: '',
      userInfo: {},
      commentList: [],
      tableData: [],
      tableDataFilter: [],
      pageNum: 1,
      pageSize: 5,
      total: 0,
      tableLoading: false,
      isVisible: false,
      dialogTitle: "",
      form: {
        squareName: "",
        squareContent: "",
      },
      rules: {
        squareName: [
          { required: true, message: "请输入名称", trigger: "blur" },
        ],
        squareContent: [
          { required: true, message: "请输入内容", trigger: "blur" },
        ],
      },
      jobSalarys: [],
      jobTags: [],
      jobExperiences: [],
      jobLocations: [],
      jobTypes: [],
      xuelis: [],
      userData: [],
      isDetail: false,
      current: {},
    };
  },
  methods: {
    naviData() {
      this.tableDataFilter = this.tableData.slice(
        (this.pageNum - 1) * this.pageSize,
        this.pageSize * this.pageNum
      );
    },
    addUser() {
      this.isVisible = true;
      this.form = {
        username: "",
        pass: "",
        checkPass: "",
        title: "",
        column: "",
      };
      this.dialogTitle = "新建用户";
    },
    handleClose() {
      this.isVisible = false;
    },
    handleCurrentChange(index) {
      this.pageNum = index;
      this.naviData();
    },
    refreshTable() {
      getSquare().then(async (res) => {
        this.tableData =
          res.code === 200 ? res.data.filter((v) => v.examine === "true") : [];
        for (let item of this.tableData) {
          let user = await getUserInfo(item.publisherId);
          item.userData = user.data;
        }
        this.total = this.tableData.length;
        this.naviData();
      });
    },
    doPublish() {
      this.isVisible = true;
      this.$nextTick(() => {
        this.$refs["form"].resetFields();
      });
    },
    commit() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          addSquare({
            ...this.form,
            examine: "",
            publisherId: this.userInfo._id,
          }).then((res) => {
            this.$message.success("等待管理员审核");
            this.refreshTable();
            this.isVisible = false;
          });
        }
      });
    },
    toDetail(row) {
      this.isDetail = true;
      this.current = row;
      this.comment = ''
      // 查看评论
      this.getComments()
    },
    addCom() {
      if (!this.comment) {
        this.$message.error('请输入评论')
        return
      }
      addComment({
        squareId: this.current._id,
        commentContent: this.comment,
        userInfo: JSON.stringify(this.userInfo)
      }).then(res => {
        if (res.code === 200) {
          this.$message.success('添加成功')
          this.getComments()
        }
      })
    },
    getComments() {
      getComments(this.current._id).then(res => {
        for (let item of res.data) {
          item.userInfo = JSON.parse(item.userInfo)
        }
        this.commentList = res.data;
      })
    },
    doDelete(data) {
      this.$confirm('此操作将永久删除该评论, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteComment(data._id).then(res => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.getComments()
        })
      })
    }
  },
};
</script>

<style lang="scss" scoped>
h1 {
  text-align: center;
  margin: 30px auto;
}
.content {
  width: 1200px;
  margin: 0 auto;
  min-height: 80vh;
  padding: 20px;
  position: relative;
  padding-top: 50px;

  .back {
    position: absolute;
    top: 10px;
    font-weight: bold;
    cursor: pointer;
    font-size: 20px;
    color: #999;
  }
}
.pagination {
  text-align: center;
  margin-top: 30px;
}
.each-square {
  padding: 20px;
  background: #f9f9f9;
  margin-top: 20px;
  border-radius: 8px;
  position: relative;
  cursor: pointer;
  img {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    margin-right: 20px;
  }
  .header {
    font-weight: bold;
  }
  .squareContent {
    font-size: 16px;
    color: #999;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 3; /*省略几行写几*/
    -webkit-box-orient: vertical;
  }

  .detail {
    position: absolute;
    right: 10px;
    top: 10px;
    right: 10px;
    color: #880088;
  }
}

.squareName {
    font-weight: bold;
    font-size: 20px;
    margin: 20px 0;
  }
.sqd {
  font-size: 16px;
  color: #999;
}

.comments {
  margin-top: 30px;
  padding: 30px 10px;
  border-top: 1px dashed #999;

  .add {
    display: flex;
    align-items: center;
    gap: 20px;
  }
}
.flex-center {
  display: flex;
  align-items: center;
  margin-bottom: 10px;

  .avator {
    width: 30px;
    height: 30px;
    border-radius: 50%;
  }
  .username {
    font-size: 16px;
    font-weight: bold;
  }
}
.each {
  padding: 10px;
  margin-top: 10px;
  position: relative;
  .delete {
    position: absolute;
    right: 10px;
    top: 10px;
    cursor: pointer;
    color: red;
  }
}
</style>
